package com.shycloud.mido.member.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.MemberRole;
import com.shycloud.mido.member.api.entity.SmMemberGoldLog;
import com.shycloud.mido.member.api.entity.SmMemberPrice;
import com.shycloud.mido.member.api.entity.SmRechargeRatio;
import com.shycloud.mido.member.api.util.Constant;
import com.shycloud.mido.member.api.vo.VipMemberVO;
import com.shycloud.mido.member.mapper.MemberMapper;
import com.shycloud.mido.member.mapper.MemberRoleMapper;
import com.shycloud.mido.member.mapper.SmMemberGoldLogMapper;
import com.shycloud.mido.member.mapper.SmRechargeRatioMapper;
import com.shycloud.mido.member.mapper.VipMemberMapper;
import com.shycloud.mido.member.service.VipMemberService;

import lombok.AllArgsConstructor;

/**
 * vip 会员模块实现类
 *
 * @author nianhua.jiang
 * @description
 * @date 2020/7/7
 */
@Service
@AllArgsConstructor
public class VipMemberServiceImpl implements VipMemberService {

	/** vip用户详情 mapper */
	private VipMemberMapper vipMemberMapper;
	/** 虚拟币充值比例 mapper */
	private SmRechargeRatioMapper rechargeRatioMapper;
	/** 用户消费信息 mapper */
	private SmMemberGoldLogMapper goldLogMapper;
	/** 会员模块 mapper */
	private MemberMapper memberMapper;
	/** vip模块 mapper */
	private MemberRoleMapper memberRoleMapper;

	/**
	 * 获取 VIP用户详情
	 *
	 * @param memberId
	 * @return com.shycloud.mido.member.api.vo.VipMemberVO
	 * @author nianhua.jiang
	 * @date 2020/7/7 10:23
	 */
	@Override
	public VipMemberVO getVipMemberDetail(String memberId) {

		VipMemberVO vipMemberDetail = vipMemberMapper.getVipMemberDetail(memberId);

		vipMemberDetail.setIsVip("1".equals(vipMemberDetail.getIsVipString()));

		///经验值
		Integer exp = vipMemberDetail.getExp();
		//等级
		Integer level = vipMemberDetail.getLevel();

		vipMemberDetail.setExp(exp < 1000 ? exp : exp - (level * 1000));
		//计算当前等级目标经验值
		vipMemberDetail.setTargetExp(1000);
		//虚拟币单位
		List<SmRechargeRatio> smRechargeRatios = rechargeRatioMapper.selectList(new QueryWrapper<>());
		vipMemberDetail.setUnit(smRechargeRatios.get(0).getUnit());
		return vipMemberDetail;
	}

	/**
	 * 续费会员
	 *
	 * @param memberPrice
	 * @param member
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/7/29 17:43
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean renewVipMember(SmMemberPrice memberPrice, Member member) {

		//==========================记录消费信息=====================//
		SmMemberGoldLog smMemberGoldLog = new SmMemberGoldLog();
		//消费的虚拟币数量
		smMemberGoldLog.setGold(memberPrice.getPriceNow());
		//用户ID
		smMemberGoldLog.setMemberId(member.getId());
		//创建时间
		smMemberGoldLog.setCreateTime(new Date());
		//方式：消费
		smMemberGoldLog.setType("0");
		//新增
		goldLogMapper.insert(smMemberGoldLog);

		//======================更新会员虚拟币的剩余数量===============//
		Integer tempGold = member.getGold() - memberPrice.getPriceNow();
		member.setGold(tempGold);
		//更新余额
		memberMapper.updateById(member);

		//TODO 会员时长累加
		MemberRole role = memberRoleMapper.selectOne(new QueryWrapper<MemberRole>()
				.eq("member_id", member.getId())
				.and(x -> x.eq("role_code", Constant.VIP_MEMBER)));

		if (role != null) {

			//创建时间
			role.setCreateTime(LocalDateTime.now());

			//如果还没到期，那么从到期时间开始累加
			if (role.getEndTime().isAfter(LocalDateTime.now())) {
				role.setEndTime(role.getEndTime().plusMonths(memberPrice.getBuyMonths()));
			}
			//如果已经到期，那么从今天开始累加会员天数
			else {
				role.setStartTime(LocalDateTime.now());
				role.setEndTime(LocalDateTime.now().plusMonths(memberPrice.getBuyMonths()));
			}
			memberRoleMapper.updMemberRole(role);
			//推送续费成功
			//pushMsg("1", vo, role);

		} else {
			//新增会员
			role = new MemberRole();
			//创建时间
			role.setCreateTime(LocalDateTime.now());
			//开始时间
			role.setStartTime(LocalDateTime.now());
			//结束时间
			role.setEndTime(LocalDateTime.now().plusMonths(memberPrice.getBuyMonths()));
			//会员
			role.setRoleCode(Constant.VIP_MEMBER);
			//用户ID
			role.setMemberId(member.getId());
			//逻辑删除
			role.setDelFlag(Constant.DEL_FLAG);
			memberRoleMapper.saveMemberRole(role);
			//推送购买成功
			//pushMsg("0", vo, role);
		}
		return true;
	}

	/**
	 * 续费会员
	 *
	 * @param optId
	 * @param duration
	 * @param memberId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2021/4/8 10:41
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean renewVipMember(Integer optId, Integer duration, String memberId) {

		if (optId != null) {
			Member member = memberMapper.selectById(memberId);
			if (optId - member.getOptId() != 0) {
				throw new BusinessException("此用户不在您的运营商下，请重新选择");
			}
		}

		// 会员时长累加
		MemberRole role = memberRoleMapper.selectOne(new QueryWrapper<MemberRole>()
				.eq("member_id", memberId)
				.and(x -> x.eq("role_code", Constant.VIP_MEMBER)));

		if (role != null) {

			//创建时间
			role.setCreateTime(LocalDateTime.now());

			//如果还没到期，那么从到期时间开始累加
			if (role.getEndTime().isAfter(LocalDateTime.now())) {
				role.setEndTime(role.getEndTime().plusDays(duration));
			}
			//如果已经到期，那么从今天开始累加会员天数
			else {
				role.setStartTime(LocalDateTime.now());
				role.setEndTime(LocalDateTime.now().plusDays(duration));
			}
			memberRoleMapper.updMemberRole(role);
			//推送续费成功
			//pushMsg("1", vo, role);

		} else {
			//新增会员
			role = new MemberRole();
			//创建时间
			role.setCreateTime(LocalDateTime.now());
			//开始时间
			role.setStartTime(LocalDateTime.now());
			//结束时间
			role.setEndTime(LocalDateTime.now().plusDays(duration));
			//会员
			role.setRoleCode(Constant.VIP_MEMBER);
			//用户ID
			role.setMemberId(memberId);
			//逻辑删除
			role.setDelFlag(Constant.DEL_FLAG);
			memberRoleMapper.saveMemberRole(role);
			//推送购买成功
			//pushMsg("0", vo, role);
		}
		return true;
	}
}
